package socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 聊天室客户端
 */
public class Client {
    /*
        java.net.Socket
        Socket封装了TCP协议的通讯细节，使用它就可以和远端计算机建立TCP连接，并基于
        两条流(一个输入一个输出流)与远端计算机交互数据。
     */
    private Socket socket;

    public Client() {
        try {
             /*
                实例化Socket就是与远端计算机建立连接的过程。
                这里参数1:服务端计算机的IP地址，参数2:服务端打开的服务端口
                我们通过IP找到服务器计算机通过端口连接到服务器上的服务端应用程序。
             */
            System.out.println("正在连接服务器");
            socket = new Socket("176.111.2.170", 8088);
            System.out.println("服务器连接完毕");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void start() {
        try {
            ServerHandler handler = new ServerHandler();
            Thread t = new Thread(handler);
            t.setDaemon(true);
            t.start();
            Scanner sca = new Scanner(System.in);
            OutputStream out = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw, true);
            while (true) {
                String line = sca.nextLine();
                if ("exit".equals(line)) {
                    break;
                }
                pw.println(line);
                pw.flush();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    public static void main(String[] args) {
        Client client = new Client();
        client.start();
    }

    private class ServerHandler implements Runnable {
        public void run() {
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                String message;
                while ((message = br.readLine()) != null) {
                    System.out.println(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}